# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import uuid
import time
import datetime
import sys
import json
import types

import redis
import socket

from django.shortcuts import render
from django.shortcuts import HttpResponse
from cmdb import models, forms
from django.contrib.auth.decorators import login_required

from django.http import JsonResponse, HttpResponseRedirect

from django.views.decorators.cache import never_cache


sys.path.append('../gen-py')
sys.path.append('./gen-py')
sys.path.append('./utils')
sys.path.append('../utils')

from utils import storage

from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol

from ServerFunction import ServerFunction

from django.db.models import Sum
from django.db.models import Count


from django.core.mail import EmailMessage
from django.template import RequestContext
from django.template import Context, Template
from django.template.loader import get_template
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect
from django.contrib import messages
from cmdb import models, forms
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from django.contrib import auth
from django.contrib.auth.decorators import login_required

from django.shortcuts import render_to_response


# Create your views here.
def ajax_data(request):
    try:
        if request.method == 'POST':
            list_login = request.body.split(':')
            user_name = list_login[0]
            password = list_login[1]
    except:
        import sys
        info = "%s || %s" % (sys.exc_info()[0], sys.exc_info()[1])
        print(info)
        ret = {'result': info}
        return JsonResponse(ret)
    models.UserInfo.objects.create(userid=uuid.uuid1(), username=user_name, pwd=password)
    ret = {'result': 'success'}
    return JsonResponse(ret)


def index_pre(request):
    if request.method == "POST":
        username = request.POST.get("username", None)
        password = request.POST.get("password", None)
        # 添加数据到数据库
        models.UserInfo.objects.create(user=username, pwd=password)
    # 从数据库中读取所有数据
    user_list = models.UserInfo.objects.all()
    # print(username, password)
    # temp = {"user": username, "pwd": password}
    # user_list.append(temp)

    return render(request, "index_pre.html", {"data": user_list})


def login(request):
    # return HttpResponse("hello world")
    return render(request, "login.html", )


def index(request):
    if request.user.is_authenticated():
        username = request.user.username
        useremail = request.user.email
    messages.get_messages(request)

    articles = models.Article.objects.values().all()

    # hostname = socket.gethostname()
    # ip = socket.gethostbyname(hostname)

    r = redis.Redis(host='127.0.0.1', port=6379, db=0, password='annanxue')
    # r.set('name', 'zhangsan')  # 添加
    # print (r.get('name'))  # 获取
    # recent_articles = r.lrange("RecentArticles", 0, 4)    # 只获取最近5个
    recent_articles = r.zrevrange("RecentArticles", 0, 33040108800)[0:4]     # 307/1/1 0:0:0

    featured = models.Comment.objects.values("article_uuid").annotate(total_comments=Count("article_uuid")).order_by('-total_comments')[0:3]    #限制3条
    # {u'article_uuid': u'd3d20da6-5d8c-11e7-907b-a6006ad3dba0', 'total_comments': 7}
    # {u'article_uuid': u'956258bd-3005-42c4-855a-6690f566f291', 'total_comments': 1}
    for comment in featured:
        for article in articles:
            if comment['article_uuid'] == article['article_uuid']:
                comment['article_title'] = article['article_title']
                break
    return render(request, "index.html", locals())


@login_required(login_url="/login/")
def home(request):
    return HttpResponse('Welcome, <a target="_blank" href="/logout/">logout</a>')


def contact(request):
    return render(request, "contact.html", )


def about(request):
    return render(request, "about.html", )


def single_article(request):
    # ttp://127.0.0.1:8000/single.html?article_id=d3d20da6-5d8c-11e7-907b-a6006ad3dba0
    article_uuid = request.GET['article_uuid']
    if request.method == 'POST':
        name = request.POST.get('name')
        email = request.POST.get('email')
        message = request.POST.get('message')
        if len(name) == 0:
            name = "游客"

        models.Comment.objects.create(article_uuid=article_uuid,comment_time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                                      comment_name=name, comment_message=message)
    article = models.Article.objects.get(article_uuid=article_uuid)
    list_comment = models.Comment.objects.filter(article_uuid=article_uuid)
    send_obj = {"comments": list_comment, "article": article}

    # add recent articles list
    r = redis.Redis(host='127.0.0.1', port=6379, db=0, password='annanxue')
    # r.lpush("RecentArticles", article.article_title)
    r.zadd("RecentArticles", article.article_title, time.time())

    return render(request, "single.html", send_obj)


def contact_message(request):
    try:
        if request.method == 'POST':
            name = request.POST.get('name')
            email = request.POST.get('email')
            body = request.POST.get('body')
    except:
        import sys
        info = "%s || %s" % (sys.exc_info()[0], sys.exc_info()[1])
        print(info)
        ret = {'result': info}
        return JsonResponse(ret)
    models.ContactMessage.objects.create(contact_time=time.time(), contact_name=name,
                                         contact_email=email, contact_body=body)
    ret = {'result': 'success'}
    return JsonResponse(ret)


def write_article(request):
    if request.method == 'POST':
        article_title = request.POST.get('article_title')
        article_content = request.POST.get('article_content')
        article_img = request.FILES.get('article_img')


        # new_img = IMG(
        #     img=request.FILES.get('img'),
        #     name=request.FILES.get('img').name
        # )
        # new_img.save()

        str_article_uuid = str(uuid.uuid1())
        models.Article.objects.create(
            article_uuid=str_article_uuid,
            article_title=article_title,
            article_author="无名氏",
            article_time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            article_content=article_content,
            article_img=article_img)

        return HttpResponseRedirect('/single.html?article_uuid=' + str_article_uuid)  # Redirect after POST

    return render(request, "writearticle.html", )


@never_cache
def date_time(request):
    if request.method == 'POST':
        num = request.POST.get('num')
        date = request.POST.get('date')
        # ret = {'result': 1099}
        # return JsonResponse(ret)
        str_ret = server_function(num, date)
        # print(type(str_ret))
        return HttpResponse(str_ret)
    if request.method == 'GET':
        return render(request, "datetime.html",)


# 图书预定
def order_book(request):
    # models.Books.objects.create(publish_date=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
    #                             price=45)

    list_book = models.Books.objects.all()
    return render(request, "orderbook.html", {"books": list_book})


def single_book(request):
    book_uuid = request.GET['book_uuid']    # get或者post请求都会传过来，url中有这个参数

    if request.method == 'POST':
        comment_content = request.POST.get('comment')
        comment_user = "游客"
        models.BookComment.objects.create(
            book_uuid=book_uuid,
            comment_user=comment_user,
            comment_content=comment_content,
            comment_time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

    book = models.Books.objects.get(book_uuid=book_uuid)

    list_comment = models.BookComment.objects.filter(book_uuid=book_uuid).order_by("-comment_time")
    print(type(list_comment))
    send_obj = {"comments": list_comment, "book": book}
    return render(request, "singlebook.html", send_obj)


def server_function(num, date):
    try:
        # Make socket
        transport = TSocket.TSocket('localhost', 9090)

        # Buffering is critical. Raw sockets are very slow
        transport = TTransport.TBufferedTransport(transport)

        # Wrap in a protocol
        protocol = TBinaryProtocol.TBinaryProtocol(transport)

        # Create a client to use the protocol encoder
        client = ServerFunction.Client(protocol)

        # Connect!
        transport.open()

        dict_ret = {}
        if date is None:
            str_ret = client.Num2DateTime(int(num))
            dict_ret = {'date': str_ret}

        elif num is None:
            int_date_time = client.DateTime2Num(date)
            str_ret = str(int_date_time)
            dict_ret = {'num': str_ret}

        str_ret = json.dumps(dict_ret)

        # Close!
        transport.close()

        return str_ret

    except Thrift.TException, tx:
        print '%s' % (tx.message)
        return ""


def index_session(request, pid=None, del_pass=None):
    if request.user.is_authenticated():
        username = request.user.username
        useremail = request.user.email
    messages.get_messages(request)
    template = get_template('index_session.html')
    request_context = RequestContext(request)
    request_context.push(locals())
    html = template.render(locals())
    return HttpResponse(html)

    # return render_to_response('my_template.html', locals(), context_instance=RequestContext(request))


@login_required(login_url='/login')
def userinfo(request):
    if request.user.is_authenticated():
        username = request.user.username
        try:
            userinfo = User.objects.get(username=username)
        except:
            pass
    template = get_template('userinfo.html')
    html = template.render(locals())
    return HttpResponse(html)


def login(request):
    if request.method == 'POST':
        login_form = forms.LoginForm(request.POST)
        if login_form.is_valid():
            login_name=request.POST['username'].strip()
            login_password=request.POST['password']
            user = authenticate(username=login_name, password=login_password)
            if user is not None:
                if user.is_active:
                    auth.login(request, user)
                    messages.add_message(request, messages.SUCCESS, '成功登录了')
                    return redirect('/')
                else:
                    messages.add_message(request, messages.WARNING, '账号尚未启用')
            else:
                messages.add_message(request, messages.WARNING, '登录失败')
        else:
            messages.add_message(request, messages.INFO, '请检查输入的字段内容')
    else:
        login_form = forms.LoginForm()

    # template = get_template('login.html')
    # request_context = RequestContext(request)
    # request_context.push(locals())
    # html = template.render(request_context)
    # html = template.render(locals())
    # return HttpResponse(html)
    return render(request, 'login.html', locals())


def logout(request):
    auth.logout(request)
    messages.add_message(request, messages.INFO, "成功注销了")
    return redirect('/')


@login_required(login_url='/login/')
def posting(request):
    if request.user.is_authenticated():
        username = request.user.username
        useremail = request.user.email

    if request.method == 'POST':
        post_form = forms.PostForm(request.POST)
        if post_form.is_valid():
            message = "您的信息已保存，要等管理员启用后才看得到。"
            post_form.save()
            return HttpResponseRedirect('/list/')
        else:
            message = '如要张贴信息，则每一个字段都要填...'
    else:
        post_form = forms.PostForm()
        message = '如要张贴信息，则每一个字段都要填...'

    template = get_template('post2db.html')
    request_context = RequestContext(request)
    request_context.push(locals())
    html = template.render(request_context)

    return HttpResponse(html)
